package com.neusoft.nep.supervise.controller;

import com.neusoft.nep.common.DataIntegrationUtils;
import com.neusoft.nep.common.Dialog;
import com.neusoft.nep.common.FileUtils;
import com.neusoft.nep.common.ViewSwitcher;
import com.neusoft.nep.supervise.entity.AQI;
import com.neusoft.nep.supervise.entity.Grid;
import com.neusoft.nep.supervise.entity.Submission;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;

import java.util.*;

public class FeedbackListViewController {
    @FXML
    private TableView tableView;
    @FXML
    private TableColumn<AQI, String> colId, colAQI, colDate, colProvince, colCity;
    @FXML
    private Button btn_back;
    @FXML
    private Button btn_commit;

    private ObservableList tableList = FXCollections.observableArrayList();
    private Map AQIMap = new HashMap();

    @FXML
    public void initialize() {
        tableView.setItems(tableList);
        colId.setCellValueFactory(new PropertyValueFactory<>("id"));
        colAQI.setCellValueFactory(new PropertyValueFactory<>("AQI"));
        colDate.setCellValueFactory(new PropertyValueFactory<>("date"));
        colProvince.setCellValueFactory(new PropertyValueFactory<>("province"));
        colCity.setCellValueFactory(new PropertyValueFactory<>("city"));

        loadAndDisplayData();
    }
    public void commitFeedback(){
        DataIntegrationUtils.integrateData();
    }

    public void back() {
        ViewSwitcher.switchView(btn_back, "../supervise/view/MainView.fxml");
    }

    private void loadAndDisplayData() {
        String gridFilePath = "grid.txt";
        String submissionFilePath = "submission.txt";

        try {

            Map<String, Submission> submissionMap = FileUtils.readMapObject(submissionFilePath);


            Map<String, Grid> gridMap =  FileUtils.readMapObject(gridFilePath);

            if (gridMap.isEmpty() || submissionMap.isEmpty()) {
                Dialog.showErrorDialog("错误", "文件中没有数据");
                return;
            }

            for (Submission submission : submissionMap.values()) {
                for (Grid grid : gridMap.values()) {
                    if (grid.getId().equals(submission.getId())) {
                        AQI aqi = new AQI(
                                submission.getId(),
                                submission.getAQI(),
                                submission.getDate(),
                                grid.getProvince(),
                                grid.getCity()
                        );
                        tableList.add(aqi);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Dialog.showErrorDialog("错误", "读取文件时发生错误: " + e.getMessage());
        }
    }
}